package com.bsj.pay.util.platform.wsgw;

import com.bsj.pay.util.platform.wsgw.sm.*;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.util.encoders.Hex;

public class SmNetworkUtil {
	private static final Logger log = LogManager.getLogger(SmNetworkUtil.class);
	
	private static String privateKeySM2="27C1FB31EF8A0AD4AA3BEA650F87EB5B89EE177DE4DD8AB9ACD0195F19E01D08";
	
	private static String publicKeySM2="048AFAE1B4C300CF6494B918C918D88CD60FE3ABD3112415BC7BA74CBAAD315BB1A44AD82B4E0B7C1FF896DE793C97BC9C3DAE3D0326F8CF2F724EEA180D238F0E";
	
	public static String generateSm4Key() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    public static String sm2De(String key,String str) {
        try {
            return new String(new SM2Utils().decrypt(Util.decodeHex(key.toCharArray()), Util.decodeHex(str.toCharArray())), "UTF-8");
        }
        catch (IOException ex) {
            ex.printStackTrace();
            return "";
        }
    }
    
    public static String sm2En(String key,String str) {
        try {
            return Util.encodeHexString(new SM2Utils().encrypt(Util.decodeHex(key.toCharArray()), str.getBytes("UTF-8")));
        }
        catch (IOException ex) {
            ex.printStackTrace();
            return "";
        }
    }
    
    public static String sm3Sign(String s) {
        final byte[] bytes = s.getBytes();
        final SM3Utils sm3Utils = new SM3Utils();
        sm3Utils.SG_SM3UpDate(bytes);
        return new String(Hex.encode(sm3Utils.SG_SM3Final()));
    }
    
    public static String sm4De(String s, final String s2) {
        final String s3 = "";
        final SM4Utils sm4Utils = new SM4Utils();
        try {
            s = new String(sm4Utils.decryptData_ECB(s.getBytes(), Hex.decode(s2.getBytes())), "UTF-8");
            return s;
        }
        catch (IOException ex) {
            ex.printStackTrace();
            s = s3;
            return s;
        }
    }
    
    public static String sm4En(final String s, final String s2) {
        return Util.byteToHex(new SM4Utils().encryptData_ECB(s.getBytes(), s2.getBytes()));
    }
    
	public static String requestBody(String body) {
		String sm4Key = SmNetworkUtil.generateSm4Key();
		String data = SmNetworkUtil.sm4En(sm4Key, body);
		JSONObject jsonObject = new JSONObject();
		long timestamp = System.currentTimeMillis();
		jsonObject.put("data", data);
		jsonObject.put("timestamp", String.valueOf(timestamp));
		String skey = sm2En(publicKeySM2, sm4Key);
		jsonObject.put("skey", skey);
		jsonObject.put("sign", sm3Sign(skey + data + timestamp));
		return jsonObject.toString();
	}

	public static String responseBody(String body) {
        JSONObject jsonObject =  JSONObject.fromObject(body);
        if(!jsonObject.containsKey("encryptData"))
        {
        	log.info("解密失败，原数据："+body);
        	return body;
        }
        String encryptData = jsonObject.getString("encryptData");
        String sm4Key = sm2De(privateKeySM2, jsonObject.getString("respKey"));
        return SmNetworkUtil.sm4De(sm4Key, encryptData);
	}
	
	public static void main(String[] args) {
		System.out.println(SmNetworkUtil.responseBody("{\"encryptData\":\"7CF2F45980884371D0383033DDCB7A0BF836B0E8D5E49A28D82A8AEE6BC162C2EEDC9FE7FF06FD4455A611BF74A6938464D9DC344AB116EF39A670D0FF1699A4DFB459268306E0AF89D046AA8D357F002707DD0AB0016DA9502F80399DB1D1DB75B062EE954624904EFA96FBDD22C7DCA210D573C2076CE719722EB879B2FCA140933A88AAF1617FC975FE1D99A57663BF2EAE60210F1CA28CEC81BFE0A4DD3943656138815542C6F775483B0E41C34C\",\"respKey\":\"049C76A4AA2B92653E6D66EA56E8ECDFF44E0FD61F234E88E71546E02F9C6D3F5E5840492725108301EA19D71F73D364542330542D2938B7534933A90B27B9E7590D54BF523789664FECA5EBDFB635597E261B07CF1BAE03C4308A9CE874BB07E424D3761A8E56ABC96E13452235EAB7A754945D1FE40C53CCB0B946BB8596F569\",\"timestamp\":1632201964404}"));
	}
}
